﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XCommunity.Frames;
using XCommunity.Views;
using System.ComponentModel;

namespace XCommunity.Views
{
  public class GeneralPostFrameView : ViewObject
  {
    public GeneralPostFrameView( ViewService service, GeneralPostFrame postFrame )
      : base( service )
    {
      PostFrame = postFrame;
    }

    public GeneralPostFrame PostFrame
    {
      get;
      private set;
    }

    /// <summary>
    /// 指示该帖子是否被修改过
    /// </summary>
    public bool IsModified
    {
      get { return PostFrame.HistoricalVersions.Any(); }
    }

    /// <summary>
    /// 话题编号
    /// </summary>
    public int TopicId
    {
      get { return PostFrame.Topic.TopicId; }
    }

    /// <summary>
    /// 帖子编号
    /// </summary>
    public Guid PostId
    {
      get { return PostFrame.Guid; }
    }


    /// <summary>
    /// 帖子原作者
    /// </summary>
    public string Author
    {
      get { return PostFrame.Author; }
    }



    private PublishedDocumentView _current;

    /// <summary>
    /// 帖子的当前版本
    /// </summary>
    public PublishedDocumentView CurrentVersion
    {
      get
      {
        if ( _current == null )
          _current = CreateDocumentView( PostFrame.CurrentVersion );

        return _current;
      }
    }


    private IEnumerable<PublishedDocumentView> _historicals;

    /// <summary>
    /// 帖子的历史版本
    /// </summary>
    public IEnumerable<PublishedDocumentView> HistoricalVersions
    {
      get
      {
        if ( _historicals == null )
          _historicals = PostFrame.HistoricalVersions.Select( document => CreateDocumentView( document ) );

        return _historicals;
      }
    }


    private IEnumerable<PublishedDocumentView> _allVersions;

    /// <summary>
    /// 帖子所有版本
    /// </summary>
    public IEnumerable<PublishedDocumentView> AllVersions
    {
      get
      {
        if ( _allVersions == null )
          _allVersions = PostFrame.GetAllVersions().Select( document => CreateDocumentView( document ) );

        return _allVersions;
      }
    }



    /// <summary>
    /// 可以在派生类中重写以创建自己的PublishedDocumentView
    /// </summary>
    /// <param name="document"></param>
    /// <returns></returns>
    protected virtual PublishedDocumentView CreateDocumentView( PublishedDocument document )
    {
      return new PublishedDocumentView( Service, document );
    }


    /// <summary>
    /// 从PostFreameView到PublishedDocumentView的隐式转换。
    /// </summary>
    /// <param name="postFrameView"></param>
    /// <returns></returns>
    public static implicit operator PublishedDocumentView( GeneralPostFrameView postFrameView )
    {
      return postFrameView.CurrentVersion;
    }


    public override object BaseObject
    {
      get { return PostFrame; }
    }
  }
}